#!/usr/bin/perl

if ( @ARGV > 0 )
{
  $path = $ARGV[0];
  $path =~ s/\\/\//g;
  $path =~ s/\/\/*/\//g;
  $path =~ s/\/$//;

  $header = 64;
  @partitions = ();
  open(XXX, "mkimage -l \"$path\"|");
  while (<XXX>)
  {
    chomp;
    if (/^\s*\Image\s+\d+:\s*(\d+)\s+Bytes/)
    {
      push(@partitions, $1);
    }
  }
  close(XXX);
  if (@partitions > 0)
  {
    # Multiple images.
    $index = 0;
    # 64 byte header, 4 byte size for each image, 4 byte terminator.
    $offset = $header + (4 * @partitions) + 4;
    while ($index < @partitions)
    {
      $size = $partitions[$index++];
      system("dd if=${path} of=${index}.img bs=1 skip=${offset} count=${size}");
      system("dd if=${index}.img of=${index}.fs bs=${header} skip=1");
      $type = `file ${index}.fs`;
      if ($type =~ /gzip compressed/)
      {
        print "${index} is compressed.\n";
        system("mv ${index}.fs ${index}.fs.gz && gzip -d ${index}.fs.gz");
      }
      $offset += $size;
    }
  }
  else
  {
    # Assume one image.
    system("dd if=${path} of=A.fs bs=1 skip=${header}");
    $type = `file A.fs`;
    if ($type =~ /gzip compressed/)
    {
      print "A is compressed.\n";
      system("mv A.fs A.fs.gz && gzip -d A.fs.gz");
    }
  }
}
